"""
字典缓存管理
提供高性能的字典数据缓存功能
"""

import logging
import time
from typing import Dict, Any, List, Optional
from threading import Lock

logger = logging.getLogger(__name__)

class DictionaryCache:
    """字典缓存类"""
    
    def __init__(self, cache_timeout: int = 300):
        """
        初始化缓存
        
        Args:
            cache_timeout: 缓存超时时间（秒），默认5分钟
        """
        self.cache_timeout = cache_timeout
        self._cache: Dict[str, Dict[str, Any]] = {}
        self._list_cache: Dict[str, Dict[str, Any]] = {}
        self._lock = Lock()
        
        # 缓存统计
        self._stats = {
            'hits': 0,
            'misses': 0,
            'sets': 0,
            'deletes': 0
        }
    
    def get_dictionary(self, dict_id: str) -> Optional[Dict[str, Any]]:
        """
        获取字典缓存
        
        Args:
            dict_id: 字典ID
            
        Returns:
            字典数据或None
        """
        with self._lock:
            if dict_id in self._cache:
                cache_item = self._cache[dict_id]
                
                # 检查是否过期
                if time.time() - cache_item['timestamp'] < self.cache_timeout:
                    self._stats['hits'] += 1
                    logger.debug(f"缓存命中: {dict_id}")
                    return cache_item['data']
                else:
                    # 删除过期缓存
                    del self._cache[dict_id]
                    self._stats['deletes'] += 1
            
            self._stats['misses'] += 1
            return None
    
    def set_dictionary(self, dict_id: str, data: Dict[str, Any]) -> None:
        """
        设置字典缓存
        
        Args:
            dict_id: 字典ID
            data: 字典数据
        """
        with self._lock:
            self._cache[dict_id] = {
                'data': data,
                'timestamp': time.time()
            }
            self._stats['sets'] += 1
            logger.debug(f"缓存设置: {dict_id}")
    
    def get_dictionary_list(self, cache_key: str) -> Optional[List[Dict[str, Any]]]:
        """
        获取字典列表缓存
        
        Args:
            cache_key: 缓存键
            
        Returns:
            字典列表或None
        """
        with self._lock:
            if cache_key in self._list_cache:
                cache_item = self._list_cache[cache_key]
                
                # 检查是否过期
                if time.time() - cache_item['timestamp'] < self.cache_timeout:
                    self._stats['hits'] += 1
                    logger.debug(f"列表缓存命中: {cache_key}")
                    return cache_item['data']
                else:
                    # 删除过期缓存
                    del self._list_cache[cache_key]
                    self._stats['deletes'] += 1
            
            self._stats['misses'] += 1
            return None
    
    def set_dictionary_list(self, cache_key: str, data: List[Dict[str, Any]]) -> None:
        """
        设置字典列表缓存
        
        Args:
            cache_key: 缓存键
            data: 字典列表
        """
        with self._lock:
            self._list_cache[cache_key] = {
                'data': data,
                'timestamp': time.time()
            }
            self._stats['sets'] += 1
            logger.debug(f"列表缓存设置: {cache_key}")
    
    def delete_dictionary(self, dict_id: str) -> bool:
        """
        删除字典缓存
        
        Args:
            dict_id: 字典ID
            
        Returns:
            是否删除成功
        """
        with self._lock:
            if dict_id in self._cache:
                del self._cache[dict_id]
                self._stats['deletes'] += 1
                logger.debug(f"缓存删除: {dict_id}")
                return True
            return False
    
    def delete_dictionary_list(self, cache_key: str) -> bool:
        """
        删除字典列表缓存
        
        Args:
            cache_key: 缓存键
            
        Returns:
            是否删除成功
        """
        with self._lock:
            if cache_key in self._list_cache:
                del self._list_cache[cache_key]
                self._stats['deletes'] += 1
                logger.debug(f"列表缓存删除: {cache_key}")
                return True
            return False
    
    def clear_cache(self) -> None:
        """清空所有缓存"""
        with self._lock:
            cache_count = len(self._cache)
            list_cache_count = len(self._list_cache)
            
            self._cache.clear()
            self._list_cache.clear()
            
            self._stats['deletes'] += cache_count + list_cache_count
            logger.info(f"缓存清空：字典缓存{cache_count}个，列表缓存{list_cache_count}个")
    
    def clear_expired_cache(self) -> int:
        """
        清理过期缓存
        
        Returns:
            清理的缓存数量
        """
        with self._lock:
            current_time = time.time()
            expired_count = 0
            
            # 清理字典缓存
            expired_keys = []
            for key, cache_item in self._cache.items():
                if current_time - cache_item['timestamp'] >= self.cache_timeout:
                    expired_keys.append(key)
            
            for key in expired_keys:
                del self._cache[key]
                expired_count += 1
            
            # 清理列表缓存
            expired_keys = []
            for key, cache_item in self._list_cache.items():
                if current_time - cache_item['timestamp'] >= self.cache_timeout:
                    expired_keys.append(key)
            
            for key in expired_keys:
                del self._list_cache[key]
                expired_count += 1
            
            if expired_count > 0:
                self._stats['deletes'] += expired_count
                logger.info(f"清理过期缓存：{expired_count}个")
            
            return expired_count
    
    def get_cache_info(self) -> Dict[str, Any]:
        """
        获取缓存信息
        
        Returns:
            缓存信息字典
        """
        with self._lock:
            total_requests = self._stats['hits'] + self._stats['misses']
            hit_rate = (self._stats['hits'] / total_requests * 100) if total_requests > 0 else 0
            
            return {
                'cache_timeout': self.cache_timeout,
                'dictionary_cache_count': len(self._cache),
                'list_cache_count': len(self._list_cache),
                'total_cache_count': len(self._cache) + len(self._list_cache),
                'hits': self._stats['hits'],
                'misses': self._stats['misses'],
                'sets': self._stats['sets'],
                'deletes': self._stats['deletes'],
                'hit_rate': round(hit_rate, 2),
                'total_requests': total_requests
            }
    
    def get_cache_keys(self) -> Dict[str, List[str]]:
        """
        获取所有缓存键
        
        Returns:
            缓存键字典
        """
        with self._lock:
            return {
                'dictionary_keys': list(self._cache.keys()),
                'list_keys': list(self._list_cache.keys())
            }
    
    def preload_cache(self, data: Dict[str, Any]) -> None:
        """
        预加载缓存数据
        
        Args:
            data: 预加载数据，格式为 {dict_id: dict_data, list_key: list_data}
        """
        with self._lock:
            current_time = time.time()
            
            for key, value in data.items():
                if isinstance(value, list):
                    # 列表数据
                    self._list_cache[key] = {
                        'data': value,
                        'timestamp': current_time
                    }
                else:
                    # 字典数据
                    self._cache[key] = {
                        'data': value,
                        'timestamp': current_time
                    }
            
            logger.info(f"预加载缓存完成：{len(data)}项")
    
    def set_cache_timeout(self, timeout: int) -> None:
        """
        设置缓存超时时间
        
        Args:
            timeout: 超时时间（秒）
        """
        self.cache_timeout = timeout
        logger.info(f"缓存超时时间设置为：{timeout}秒")
    
    def reset_stats(self) -> None:
        """重置缓存统计"""
        with self._lock:
            self._stats = {
                'hits': 0,
                'misses': 0,
                'sets': 0,
                'deletes': 0
            }
            logger.info("缓存统计已重置")


# 全局缓存实例
_dictionary_cache = None

def get_dictionary_cache() -> DictionaryCache:
    """
    获取全局字典缓存实例
    
    Returns:
        字典缓存实例
    """
    global _dictionary_cache
    if _dictionary_cache is None:
        _dictionary_cache = DictionaryCache()
    return _dictionary_cache

def reset_dictionary_cache() -> None:
    """重置全局字典缓存实例"""
    global _dictionary_cache
    _dictionary_cache = None